﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using Web.Account;
using Web.Security;

namespace AssetManage.Handler
{
    public class Email : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext currentContext)
        {
            var action = currentContext.Request.Params["action"];
            var username = currentContext.Request.Params["username"];
            var email = currentContext.Request.Params["email"];

            var responseJsonStringBuilder = new StringBuilder();
            var responseJsonStringWriter = new StringWriter(responseJsonStringBuilder);
            var responseJsonWriter = new JsonTextWriter(responseJsonStringWriter) {Formatting = Formatting.Indented};
            responseJsonWriter.WriteStartObject();

            switch (action)
            {
                case "send":
                    if (!Regex.IsMatch(email, @"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$"))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_Error");
                        break;
                    }
                    if (AccountManage.IsExistEmail(email))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_IsExist");
                        break;
                    }
                    var emailCaptcha = RandomString.GetRandomString();
                    currentContext.Session["EMAIL_CAPTCHA"] = emailCaptcha;
                    var number = 0;
                    if (!String.IsNullOrEmpty((String) currentContext.Session["NUMBER"]))
                    {
                        number = Convert.ToInt32(currentContext.Session["NUMBER"]);
                    }
                    if (Web.Account.Email.SendEmail(email, username, number + 1, emailCaptcha))
                    {
                        number++;
                        currentContext.Session["NUMBER"] = number.ToString(CultureInfo.InvariantCulture);
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                        responseJsonWriter.WritePropertyName("id");
                        responseJsonWriter.WriteValue(number.ToString("D2"));
                    }
                    else
                    {
                        currentContext.Session["NUMBER"] = number.ToString(CultureInfo.InvariantCulture);
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Send_Error");
                    }
                    break;
                case "reset":
                    if (currentContext.Request.Cookies["ASP.NET_SessionId"] == null)
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Cookie_Error");
                    }
                    if (!Regex.IsMatch(email, @"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$"))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_Error");
                        break;
                    }
                    if (!AccountManage.IsExistEmail(email))
                    {
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(false);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Email_IsNotExist");
                        break;
                    }
                    var resetEmailCaptcha = RandomString.GetRandomString();
                    currentContext.Session["EMAIL_CAPTCHA"] = resetEmailCaptcha;
                    var resetNumber = 0;
                    if (!String.IsNullOrEmpty((String) currentContext.Session["NUMBER"]))
                    {
                        resetNumber = Convert.ToInt32(currentContext.Session["NUMBER"]);
                    }
                    var userid = AccountManage.GetUserID(email);
                    if (Web.Account.Email.SendResetPasswordEmail(email,
                        AccountManage.GetRealName(AccountManage.GetTableID(userid)),
                        userid, resetNumber + 1, resetEmailCaptcha))
                    {
                        resetNumber++;
                        currentContext.Session["NUMBER"] = resetNumber.ToString(CultureInfo.InvariantCulture);
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                        responseJsonWriter.WritePropertyName("id");
                        responseJsonWriter.WriteValue(resetNumber.ToString("D2"));
                    }
                    else
                    {
                        currentContext.Session["NUMBER"] = resetNumber.ToString(CultureInfo.InvariantCulture);
                        responseJsonWriter.WritePropertyName("success");
                        responseJsonWriter.WriteValue(true);
                        responseJsonWriter.WritePropertyName("error");
                        responseJsonWriter.WriteValue("Send_Error");
                    }
                    break;
            }
            responseJsonWriter.WriteEndObject();
            currentContext.Response.Write(responseJsonStringBuilder.ToString());
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}